package com.cai.seckill.common.exception;

import com.cai.seckill.common.vo.RespBean;
import com.cai.seckill.common.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @BelongsProject secKill
 * @Package com.cai.seckill.common.exception
 * @Author Uli1024
 * @CreaterTime 2022/8/4 21:09
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(GlobalException.class)
    public RespBean ExceptionHandler(GlobalException e) {
        log.error("全局异常处理-------------{}", e.getRespBeanEnum().getMessage());
        return RespBean.error(e.getRespBeanEnum());
    }

    @ExceptionHandler(BindException.class)
    public RespBean ExceptionHandler(BindException e) {
        RespBean respBean = RespBean.error(RespBeanEnum.BIND_ERROR);
        String msg = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        log.error("参数校验异常-------------{}", msg);
        respBean.setMessage("参数校验异常：" + msg);
        return respBean;
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public RespBean ExceptionHandler(IllegalArgumentException e) {
        log.error("断言异常-------------{}", e.getMessage());
        return RespBean.error(RespBeanEnum.ASSERT_ERROR).setMessage(e.getMessage());
    }
}

